<template>
  <div class="user-manage w-full h-full display-flex">
    <div class="left-search h-full">
      <a-tree
        bordered
        v-if="treeData.length > 0"
        v-model="selectedOrg"
        @select="onSelect"
        :tree-data="treeData"
        :defaultExpandAll="true"
        :replace-fields="replaceFields"
      >
      </a-tree>
    </div>
    <div class="right-table h-full">
      <div class="top-btns w-full">
        <a-space>
          <a-button @click="userAdd" type="primary">新增</a-button>
          <a-button @click="userModify" type="primary" :disabled="table.rowSelection.selectedRowKeys.length<1">修改
          </a-button>
          <a-button @click="userDelete" type="primary" :disabled="table.rowSelection.selectedRowKeys.length<1">删除
          </a-button>
          <a-input-search
            v-model="filter.filterText"
            placeholder="请输入查询条件"
            @search="loadData"
            style="width: 300px;"
            enter-button
          />
        </a-space>
      </div>
      <a-table
        style="height:calc(100% - 40px);overflow-y:auto;"
        bordered
        :row-selection="table.rowSelection"
        :rowKey="record => record.id"
        :columns="table.columns"
        :data-source="table.dataSource"
        :pagination="table.pagination"
      >
        <template slot="state" slot-scope="text">
          {{ judgeState(text) }}
        </template>
        <span slot="appKey" slot-scope="text">{{text}}</span>
        <span slot="appSecret" slot-scope="text, row">
          <a @click.stop.prevent="showAppSecret(row)" class="a-edit" title="点击获取应用密钥">********</a>
        </span>
        <span slot="opt" slot-scope="text, row" style="font-size: 8px;">
          <span title="复制应用账号信息"><a @click.stop.prevent="copyAppInfo(row)">复制</a></span> |
          <span title="锁定该应用账号信息"><a @click.stop.prevent="lockUser(row)">锁定</a></span> |
          <span title="重置该应用账号密钥"><a @click.stop.prevent="resetAppSecret(row)">重置密钥</a></span><!-- |
          <span><a @click.stop.prevent="showAppSecret(row)">重置密钥</a></span>-->
        </span>
      </a-table>
    </div>
  </div>
</template>

<script>
  import orupService from '@/api/orupService'
  import systemManageService from '@/api/systemManageService'
  import moment from 'moment'

  const columns = [
    {
      title: '用户名',
      align: 'center',
      dataIndex: 'appName'
    },
    {
      title: 'AppKey',
      align: 'center',
      dataIndex: 'appKey'
    },
    {
      title: 'AppSecret',
      align: 'center',
      dataIndex: 'appSecret',
      scopedSlots: {customRender: 'appSecret'}
    },
    {
      title: '排序',
      align: 'center',
      dataIndex: 'sortNum'
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'state',
      scopedSlots: {customRender: 'state'}
    },
    {
      title: '注册时间',
      align: 'center',
      dataIndex: 'registerTime',
      customRender: (text) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    {
      title: '操作',
      align: 'center',
      scopedSlots: {customRender: 'opt'}
    }
  ]

  export default {
    name: 'UserManage',

    data() {
      return {
        search: '',
        treeData: [],
        selectedOrg: [],
        stateList: [],
        expandedKeys: [],
        replaceFields: {
          key: 'id',
          title: 'name',
          children: 'children'
        },
        filter: {
          filterText: '',
          pageIndex: 1,
          pageSize: 10
        },
        table: {
          columns: columns,
          dataSource: [],
          rowSelection: {
            selectedRowKeys: [],
            selectedRow: {},
            onChange: (selectedRowKeys, selectedRows) => {
              this.table.rowSelection.selectedRowKeys = selectedRowKeys.length ? [selectedRowKeys.pop()] : []
              this.table.rowSelection.selectedRow = selectedRows.length ? selectedRows.pop() : {}
            }
          },
          pagination: {
            pageSize: 10,
            total: 0,
            current: 1,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100', '200', '500'],
            showTotal: (total) => `共${total}条数据`,
            onShowSizeChange: (current, pageSize) => {
              this.filter.pageIndex = 1
              this.filter.pageSize = pageSize
            },
            onChange: (current, pageSize) => {
              this.filter.pageIndex = current
              this.filter.pageSize = pageSize
              this.table.pagination.current = current
            }
          }
        }
      }
    },

    mounted() {
      this.loadData()
      this.getOrgData()
    },

    methods: {
      moment,
      loadData() {
        const params = {
          pageIndex: this.filter.pageIndex - 1,
          pageSize: this.filter.pageSize,
          filterText: this.filter.filterText,
          userState: 0
        }
        orupService.userManageListQuery(params).then(res => {
          if (res && res.length > 0) {
            this.table.dataSource = res
          } else {
            this.$message.warning('没有相关用户!')
            this.filter.filterText = ''
          }
        })
      },
      async getOrgData() {
        this.stateList = await orupService.userManageStateListQuery()
        this.treeData = await orupService.orgManageTreeQuery({})
      },
      onSelect(list) {
        this.selectedOrg = list
      },
      userAdd() {
        if (this.selectedOrg.length < 1) {
          this.$message.warning('请先选择左侧组织机构!')
        } else {
          this.showDialog()
        }
      },
      userModify() {
        this.showDialog(this.table.rowSelection.selectedRow)
      },
      showDialog(record) {
        const _this = this
        this.$dialog({
          title: '新建用户',
          content: () => import('@v/investmentOnline/systemManage/dialog/UserDialog.vue'),
          width: 500,
          bodyStyle: {height: '290px'},
          props: {
            record: record
          },
          centered: true,
          maskClosable: false,
          on: {
            ok(ctl) {
              const dialogCtl = ctl.getDialogCtl()
              if (dialogCtl.onSubmit()) {
                if (record && record.id) {
                  orupService.userManageUpdate(dialogCtl.form).then(res => {
                    if (res && res.id) {
                      _this.$message.success('修改成功!')
                      _this.loadData()
                      _this.table.rowSelection.selectedRowKeys = []
                      _this.table.rowSelection.selectedRow = {}
                    }
                  })
                } else {
                  orupService.userManageSave(_this.selectedOrg.pop(), dialogCtl.form).then(res => {
                    if (res && res.id) {
                      _this.$message.success('添加成功!')
                      _this.loadData()
                      _this.selectedOrg = []
                    }
                  })
                }
                ctl.closeDialog()
              }
            }
          }
        })
      },
      userDelete() {
        const _this = this
        this.$confirm({
          title: '提示',
          content: '确认删除该数据吗？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            const row = _this.table.rowSelection.selectedRow
            orupService.userManageDelete(row).then(res => {
              if (res) {
                _this.loadData()
                _this.$message.success('删除成功!')
              }
            })
          }
        })
      },
      judgeState(text) {
        const data = this.stateList.filter(item => {
          return item.state === text
        })
        if (data && data.length > 0) {
          return data[0].description
        } else {
          return ''
        }
      },
      showAppSecret(record) {
        systemManageService.userInfoCopy({appId: record.id}).then(res => {
          this.$dialog({
            title: '应用[' + record.appName + ']密钥',
            content: () => import('@v/investmentOnline/systemManage/dialog/UserSecretDialog.vue'),
            width: 550,
            props: {
              record: res
            },
            centered: true,
            maskClosable: false,
            on: {
              ok(ctl) {
                ctl.closeDialog()
              }
            }
          })
        })
      },
      copyAppInfo(record) {
        systemManageService.userInfoCopy({appId: record.id}).then(res => {
          const copyText = "appName:" + res.appName + "\n"
            + "appKey:" + res.appKey + "\n"
            + "appSecret:" + res.appSecret + "\n";
          this.copyToClipboard(copyText);
          this.$message.success('应用信息已复制到粘贴板!');
        })
      },
      resetAppSecret(record) {
        this.$confirm({
          content: '确认重置该账号密钥？',
          okType: 'danger',
          onOk: () => {
            systemManageService.resetUserAppSecret({appId: record.id}).then(res => {
              this.$message.success('应用密钥信息已更新，请及时替换!');
              this.loadData();
            })
          }
        })
      },
      lockUser(record) {
        this.$confirm({
          content: '确认锁定该账号？',
          okType: 'danger',
          onOk: () => {
            systemManageService.lockUser({appId: record.id}).then(res => {
              this.$message.success('应用账号已锁定');
              this.loadData();
            })
          }
        })
      },
      copyToClipboard(text) {
        // 创建一个虚拟的DOM元素
        const element = document.createElement('textarea');
        element.value = text;
        document.body.appendChild(element);

        // 选中文本
        element.select();
        element.setSelectionRange(0, element.value.length);

        // 执行复制命令
        document.execCommand('copy');

        // 清理虚拟DOM元素
        document.body.removeChild(element);
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-manage {
    padding: 10px;
    background: #fff;
    .left-search {
      width: 20%;
    }
    .right-table {
      width: 80%;
      padding-left: 10px;
      .top-btns {
        height: 40px;
      }
    }
  }

</style>
